# coding=utf-8

from . import admin
from flask import request, render_template, jsonify
from app import PAGE_NUM, page_code, util
from dbConnection.MysqlConn import Mysql
import math, time
import sys
import urllib
from app.business import login
reload(sys)
sys.setdefaultencoding('utf8')


# 商家添加套餐
@admin.route('/admin/add_card.html')
@util.admin_login
def add_card():
    bid = request.values.get('bid')
    res = get_user_detail(bid)
    taocan = get_taocan()
    return render_template('admin/business/add_card.html', res=res, taocan=taocan)


# 商家新增购买套餐
@admin.route('/admin/add_business_pay_post', methods=['post'])
@util.admin_login
def add_business_pay_post():
    tc = request.values.get('tc')
    num = request.values.get('num')
    bid = request.values.get('bid')
    user = get_user_detail(bid)
    taocan = get_taocan_detail(tc)
    data = {}
    data['status'] = 0
    if user is None:
        data['status'] = 2
        return jsonify(data)
    if taocan is None:
        data['status'] = 3
        return jsonify(data)
    res = add_orders(bid, num, taocan)
    if res > 0:
        data['status'] = 1
    return jsonify(data)


# 商家订单列表
@admin.route('/admin/business_order.html')
@util.admin_login
def business_order():
    business = get_all_business()
    return render_template('admin/business/business_order.html', business=business)


# 获取商家订单列表数据
@admin.route('/admin/business_order_data_post', methods=['post'])
@util.admin_login
def business_order_data_post():
    parms = ['uid', 'stime', 'etime']
    maps = {}
    for d in parms:
        maps[d] = request.values.get(d)
    p = request.values.get('p', 1)
    c_num = (int(p) - 1) * PAGE_NUM
    sql = "select p.*, b.username, b.nickname FROM business_pay_log p LEFT JOIN user_business b ON b.bid = p.bid WHERE 1=1"
    sql2 = "select count(*) con FROM business_pay_log p LEFT JOIN user_business b ON b.bid = p.bid WHERE 1=1"
    if maps['uid']:
        sql += " and p.bid = '%s'" % maps['uid']
        sql2 += " and p.bid = '%s'" % maps['uid']
    if maps['stime']:
        sql += " and p.add_time >= '%s'" % maps['stime']
        sql2 += " and p.add_time >= '%s'" % maps['stime']
    if maps['etime']:
        etime_str = maps['etime'] + ' 23:59:59'
        sql += " and p.add_time <= '%s'" % etime_str
        sql2 += " and p.add_time <= '%s'" % etime_str
    sql += " order by p.add_time desc limit %d, %d" % (c_num, PAGE_NUM)
    mysql = Mysql()
    res = mysql.getAll(sql, None)
    cont = mysql.getOne(sql2, None)
    mysql.dispose()
    pages = int(math.ceil(cont['con'] / float(PAGE_NUM))) if cont else 0
    route_path = 'get_data'
    html_str = page_code.page_code_html_post(int(p), route_path, pages) if pages > 0 else ''
    data = {}
    data['status'] = 2
    data['page'] = html_str
    data['p'] = p
    if res:
        for d in res:
            d['add_time'] = str(d['add_time'])
            d['recharge_price'] = str(d['recharge_price'])
            d['pay_money'] = str(d['pay_money'])
        data['res'] = res
        data['status'] = 1
    return jsonify(data)


# 商家赠送记录列表
@admin.route('/admin/give_list.html')
@util.admin_login
def give_list():
    business = get_all_business()
    return render_template('admin/business/give_list.html', business=business)


# 商家赠送记录列表
@admin.route('/admin/give_list_data_post', methods=['post'])
@util.admin_login
def give_list_data_post():
    parms = ['uid', 'stime', 'etime']
    maps = {}
    for d in parms:
        maps[d] = request.values.get(d)
    p = request.values.get('p', 1)
    c_num = (int(p) - 1) * PAGE_NUM
    sql = "select g.*, r.name,r.num, t.use_num, u.wxNickName, b.nickname,n.wxNickName as wxName FROM business_give_log g LEFT JOIN recharge r ON r.id = g.rid LEFT JOIN " \
          "user_taocan t ON t.id = g.tid LEFT JOIN car_users u ON u.uid = g.uid left join car_users n on n.uid=g.give_uid LEFT JOIN user_business b ON b.bid = g.bid WHERE 1=1"
    sql2 = "select count(*) con, sum(r.num) as total_num FROM business_give_log g LEFT JOIN car_users u ON u.uid = g.uid  left join recharge r on r.id = g.rid WHERE 1=1"
    if maps['uid']:
        sql += " and g.bid = '%s'" % maps['uid']
        sql2 += " and g.bid = '%s'" % maps['uid']
    if maps['stime']:
        sql += " and g.add_time >= '%s'" % maps['stime']
        sql2 += " and g.add_time >= '%s'" % maps['stime']
    if maps['etime']:
        etime_str = maps['etime'] + ' 23:59:59'
        sql += " and g.add_time <= '%s'" % etime_str
        sql2 += " and g.add_time <= '%s'" % etime_str
    sql += " order by g.add_time desc limit %d, %d" % (c_num, PAGE_NUM)
    mysql = Mysql()
    res = mysql.getAll(sql, None)
    cont = mysql.getOne(sql2, None)
    mysql.dispose()
    pages = int(math.ceil(cont['con'] / float(PAGE_NUM))) if cont else 0
    route_path = 'get_data'
    html_str = page_code.page_code_html_post(int(p), route_path, pages) if pages > 0 else ''
    data = {}
    data['status'] = 2
    data['page'] = html_str
    data['p'] = p
    if res:
        for d in res:
            d['add_time'] = str(d['add_time'])
            d['wxNickName'] = d['wxNickName'] if d['wxNickName'] else '未知'
            d['qr_code'] = urllib.quote(login.business_url(d['bid'],d['id']))
            if d['uid'] > 0:
                if d['use_num'] > 0:
                    d['status'] = '已使用'
                else:
                    d['status'] = '未使用'

            else:
                d['status'] = '未领取'
            if d['wxName']  is None:
                d['wxName'] =""
        data['count'] = cont['con']
        data['total_num'] =cont['total_num']
        data['res'] = res
        data['status'] = 1

    return jsonify(data)


# 新增商家购买订单
def add_orders(bid, num, res):
    sql = "insert into business_pay_log(bid, recharge_id, num, recharge_num, recharge_name, recharge_price, pay_money, " \
          "useful_time, add_time) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s'," \
          " now())" % (bid, res['id'], num, res['num'], res['name'], res['price'], float(res['price'])*float(num), res['stopTime'])
    mysql = Mysql()
    res = mysql.insertOne(sql, None)
    mysql.dispose()
    return res


# 获取所有商家
def get_all_business():
    sql = "select * FROM user_business"
    mysql = Mysql()
    res = mysql.getAll(sql, None)
    mysql.dispose()
    return res


# 获取用户详情
def get_user_detail(uid):
    sql = "select * FROM user_business WHERE bid = '%s'" % uid
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    mysql.dispose()
    return res


# 获取套餐详情
def get_taocan_detail(tid):
    sql = "select * FROM recharge WHERE id = '%s'" % tid
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    mysql.dispose()
    return res


# 获取所有套餐
def get_taocan():
    sql = "select * FROM recharge where status = 1"
    mysql = Mysql()
    res = mysql.getAll(sql, None)
    mysql.dispose()
    return res